#include "UIHelper.h"
#include <QMessageBox>
#include <QPushButton>
#include <QTime>
#include <QAbstractEventDispatcher>
#include <QThread>

int showMessagebox(const QString &title, const QString &text, int icon){
    static QMessageBox * box = nullptr;
    if(!box){
        box = new QMessageBox(0);
        QPushButton * ok = box->addButton(QMessageBox::Ok);
        ok->setText("确定");
        QPushButton * cancel = box->addButton(QMessageBox::Cancel);
        cancel->setText("取消");
    }
    box->setWindowTitle(title);
    box->setIcon(QMessageBox::Icon(icon));
    box->setText(text);

    return box->exec();
}

void showMessageWithUnmode(const QString &title, const QString &text, int icon,QWidget *parent){
    QMessageBox * box = new QMessageBox(parent);
    box->setModal(false);
    box->setAttribute(Qt::WA_DeleteOnClose);//关闭对话框自动析构
    box->setWindowTitle(title);
    box->setIcon(QMessageBox::Icon(icon));
    box->setText(text);
    QPushButton * ok = box->addButton(QMessageBox::Ok);
    ok->setText("关闭");
    QObject::connect(ok,&QPushButton::clicked,[box](){box->close();});
    box->activateWindow();
    box->showNormal();
    box->raise();
}

void g_mySleep(float sec){
    QTime t;
    t.start();
    sec *= 1000;
    QAbstractEventDispatcher * dispatcher = QThread::currentThread()->eventDispatcher();
    if(dispatcher == NULL){
        return;
    }
    /*关于误差：很小，因t.elapsed()是一直在走的，产生的时差是当无限接近于sec，然后休眠100ms，此时将产生±100ms
     *关于休眠：1.是为了让出cpu，使线程可以执行其他线程。2：分配事件派发的时间。
    */
    while(t.elapsed() < sec){
        dispatcher->processEvents(QEventLoop::AllEvents);
        QThread::currentThread()->usleep(100);
    }
}
